/**
 * 
 */
package com.kandinfo.base.common.util;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * @author tangqh
 *
 */
public class Global {
	private static Logger log = LoggerFactory.getLogger(Global.class);
	private static Map<String, Long> maxIdMap = new HashMap<String, Long>();
	/**
	 * 获取最大id 
	 */
	public synchronized static Long getMaxIdByTable(String tableName) {
		Long maxId = maxIdMap.get(tableName);
		if (maxId == null || maxId == 0L) {
			initMaxOrderId(tableName);// 数据库最大题号
		}
		maxIdMap.put(tableName, (maxId = maxIdMap.get(tableName) + 1));
		return maxId;
	}
	
	public static void main(String[] args) {
		System.out.println(getTranId(11L) + "");
	}
	
	/**
	 * 获取当天订单号
	 */
	public synchronized static Long getTranId(Long mchId) {
		String todayString = new SimpleDateFormat("yyyyMMdd").format(new Date());
		String yesterdayKey = mchId + String.valueOf(Long.valueOf(todayString) - 1), todeyKey = mchId + todayString;
		Long tranId = maxIdMap.get(todeyKey);
		if (tranId == null || tranId == 0L) {
			maxIdMap.remove(yesterdayKey);
			maxIdMap.put(todeyKey, new Long(100000000));
		}
		maxIdMap.put(todeyKey, (tranId = maxIdMap.get(todeyKey) + 1));
		return tranId;
	}

	/**
	 * 获取最大ID
	 */
	private static void initMaxOrderId(String tableName) {
		Connection connection = JdbcConnection.getConnection();
		PreparedStatement preparedStatement = null;
		ResultSet resultSet = null;
		try {
			String sql = "select max(id) id from " + tableName;
			preparedStatement = connection.prepareStatement(sql);
			resultSet = preparedStatement.executeQuery();
			if (resultSet.next()) {
				do {
					maxIdMap.put(tableName, resultSet.getLong("id"));
				} while (resultSet.next());
			}
		} catch (Exception e) {
			log.error("", e);
		} finally {
			JdbcConnection.close(resultSet, preparedStatement, connection);
		}
	}
}
